from odoo import api, models, fields, _
from odoo.exceptions import ValidationError
import logging

_logger = logging.getLogger(__name__)


class SbSaleLinkMo(models.Model):
    _inherit = 'sb.sale.link.mo'

    delink_apply_id = fields.Many2one('delink.apply', string='Line/Delink Apply')

    @api.onchange('delink_apply_id')
    def onchange_info(self):
        self.line_ids = None
        if not self.delink_apply_id: return
        self.link_mo = self.delink_apply_id.link_mo
        self.delink_mo = self.delink_apply_id.delink_mo
        self.sale_order_id = self.delink_apply_id.sale_order_id.id
        line_vals = []
        for line in self.delink_apply_id.line_ids:
            line_vals.append((0, 0, {
                'mrp_production_id': line.mrp_production_id.id,
                'sale_order_line_id': line.sale_order_line_id.id,
                'is_option': True
            }))
        # print(line_vals)
        self.write({'line_ids': line_vals,
                    'delink_mo': self.delink_apply_id.delink_mo,
                    'sale_order_id': self.delink_apply_id.sale_order_id.id,
                    'link_mo': self.delink_apply_id.link_mo})
        # self.line_ids = line_vals

    def button_cancel(self):
        self.delink_apply_id = None
        return super().button_cancel()
